package wechat

import (
	"bytes"
	"crypto/tls"
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego/logs"
	"io"
	"io/ioutil"
	"net/http"
	"os"
	"strings"
)

type MiniSceneQrcode struct {
	Scene       string `json:"scene"`
	Page        string `json:"page"`
	Width       int    `json:"width"`
}

type MiniSceneQrcodeRes struct {
	Errcode     int    `json:"errcode"`
	Errmsg      string `json:"errmsg"`
	ContentType string `json:"contentType"`
}

func CreateMiniSceneQrcode(scene, page, imgName string, width int) (string, error) {
	accessToken := GetMiniAccessToken()
	miniSceneQrcode := MiniSceneQrcode{
		Scene:       scene,
		Page:        page,
		Width:       width,
	}
	content, err := json.Marshal(miniSceneQrcode)
	if err != nil {
		logs.Error("can not marshal mini scene qrcode struct:", err)
		return "", err
	}

	url := fmt.Sprintf("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=%s", accessToken)
	req, _ := http.NewRequest("POST", url, strings.NewReader(string(content)))
	req.Header.Set("Content-Type", "application/json")
	tr := &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	}
	client := &http.Client{Transport: tr}
	resp, err := client.Do(req)
	if err != nil {
		logs.Error("send wechat create scene qrcode request fail:", err)
		return "", err
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		logs.Error("can not read from wechat create scene qrcode response:", err)
		return "", err
	}

	logs.Info("qrcode:", string(body))

	dir := "./static/qrcode/"
	if _, err := os.Stat(dir); err != nil {
		err = os.MkdirAll(dir, os.ModePerm)
		if err != nil {
			logs.Error("can not create qrcode dir:", err)
			return "", err
		}
	}

	name := fmt.Sprintf("%s%s", dir, imgName)
	qrcode, err := os.Create(name)
	defer qrcode.Close()
	_, err = io.Copy(qrcode, bytes.NewReader(body))
	if err != nil {
		logs.Error("can not save mini scene qrcode:", err)
		return "", err
	}

	return strings.TrimLeft(name, "."), nil
}
